var SERVERURL = "http://mww5.xuanwumobile.com/";


/////////////////////////首页//////////////////
var main1index=SERVERURL+'api/Index/index';

var shopInfo=SERVERURL+'api/Index/shopInfo';

var shopInfoMain= SERVERURL+'api/Index/shopInfoMain';

var shopGoodList =  SERVERURL+'api/Index/shopGoodList';//分类详情

var shopGoodInfo =SERVERURL+'api/Index/shopGoodInfo';//商品详情

var putGoodInCar =SERVERURL+'api/Index/putGoodInCar';//加入购物车

var getAddress=SERVERURL+'api/Index/getAddress';//收货地址列表

var getOneAddress=SERVERURL+'api/Index/getOneAddress';//某一个收货地址详情

var addAddress=SERVERURL+'api/Index/addAddress';//新增地址

var updateAddress=SERVERURL+'api/Index/updateAddress';//编辑地址

var deleteAddress= SERVERURL+'api/Index/deleteAddress';//删除

//////////////////购物车//////////////////////

var myCar = SERVERURL+'api/Order/myCar';//我的购物车page

var deleteMyCar = SERVERURL+'api/Order/deleteMyCar';//删除购物车

var sureOrder = SERVERURL+'api/Order/sureOrder';//确认订单页

var makeOrder = SERVERURL+'api/Order/makeOrder';//生成订单

var getNearAddress = SERVERURL+'api/Order/getNearAddress';//查看可以送的地址

var myOrderInfo = SERVERURL+'api/Order/myOrderInfo';//订单详情

var cancelOrder=SERVERURL+'api/Order/cancelOrder';//取消订单

var onlyPay =SERVERURL+'api/Order/onlyPay';//取消订单

var getMyOrder = SERVERURL+'api/Order/getMyOrder';//确认收货

var commentMyOrder =SERVERURL+'api/Order/commentMyOrder';//评价

var tuikuan =SERVERURL+'api/Order/tuikuan';//申请退款

///////////////////////////////我的 ////////////////////////
var main3index = SERVERURL+'api/My/index';
var myInfo= SERVERURL+'api/My/myInfo';

var myOrder = SERVERURL+'api/Order/myOrder';

var notice =  SERVERURL+'api/My/notice';

var feedbackTypes=  SERVERURL+'api/My/feedbackTypes';

var feedback = SERVERURL+'api/My/feedback';

//////////////////////////登录//////////////////
var userLogin =SERVERURL+'api/Login/userLogin';
var getPhoneCode= SERVERURL+'api/Login/getPhoneCode';
var userReg =  SERVERURL+'api/Login/userReg';
var forgetPass =  SERVERURL+'api/Login/forgetPass';

var wqLogin =SERVERURL+'api/Login/wqLogin';
var wqFirstLogin = SERVERURL+'api/Login/wqFirstLogin';

//////////七牛相关///////////
//var yasuoimgggggg='?imageMogr2/quality/25!';
//var getFileToken ="http://mms.mangmeshi.com/admin/Common/getQiniuToken";
//var IMAGEURL = "http://qiniu.mangmeshi.com/"; //七牛云地址


var yasuoimgggggg='?imageMogr2/quality/25!';
var getFileToken="http://mww5.xuanwumobile.com/api/My/getQiniuToken";
var IMAGEURL='http://pgbmxvvaa.bkt.clouddn.com/';//七牛云地址


var qiNiuKey = new Date().getTime() + '.jpg';
var qiNiuKey2 = new Date().getTime() + '.mp4';
function qiNiuKeyName(){
    var qiNiuKey = new Date().getTime()+'.jpg';
    return qiNiuKey;
}
function qiNiuKeyName2(){
    var qiNiuKey = new Date().getTime()+'.mp4';
    return qiNiuKey;
}

//除了2收货其他列表
function getMP4Img(video){

video=video+'?vframe/jpg/offset/1/q/100!.png|imageView2/1/w/720/h/166'

return video

}

var page='1';
/**
 *  网络数据请求
 * @param {Object} url  链接的服务器地址
 * @param {Object} type   传递的是 GET  OR POST
 * @param {Object} params   参数   JSON 参数   values:JSON 参数    files 表示你要上传的文件
 * @param {Object} successFun   成功的执行方法
 * @param {Object} errorFun  失败的执行方法

	例子：
	var parame = {
		values : {
		}
	}
	doAjax(url, "POST", parame, function(successData) {
	//成功执行函数
	}, function(errorData) {
	//失败执行函数
	})

 */

var doAjax = function(url, type, params, successFun, errorFun) {

	//console.log(JSON.stringify($api.getStorage("allUser")));

	if($api.getStorage("allUser")){
    var value = $api.getStorage("allUser").user_token || "";
    var user_id = $api.getStorage("allUser").user_id || "0";



    }else{
    var value="";
    var user_id="0";


    }

    if (params.values == null) {
        params.values = {}
    }

    var  reqDate = Date.now();
    var appId = "A6070308312682";
    var appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
    var reqKey = MD5(appId + "XW" + appkey + "XW" +  reqDate);
    var Token = MD5(user_id + "XW" + value + "XW" +  reqDate);


    params.values.value = Token;
    params.values.user_id = user_id;
	params.values.time = reqDate;
	params.values.reqKey = reqKey;

    console.warn("接口地址和入参！！" + url + "  " + JSON.stringify(params)+"时间戳："+reqDate+"加密key："+reqKey);

    api.ajax({
        url: url,
        method: type,
        data: params,
        headers: {
            reqKey: reqKey,
            time: reqDate
        },
        timeout: 30
    }, function(ret, err) {

        if (ret) {
            console.warn("接口成功返回！！" + JSON.stringify(ret));

            if (ret.status == '301') {

                api.alert({
                    title: '账号异常',
                    msg: '账号已在其他地方登录,请重新登录',
                }, function(ret, err) {

					$api.rmStorage('allUser');

					api.rebootApp();
                });
            }
            successFun(ret);
        } else {
            LoadingClose();
            api.refreshHeaderLoadDone();
            errorFun(err);
            console.warn("接口返回失败！！" + JSON.stringify(err));
            api.toast({
                msg: '网络连接超时',
                location: "middle"
            });
        }

    });
}


/**
 *打开win例子：
	 var parame  = {
	 	 rowid : rowid
	  }
	  openWindow("chat_win", "chat_win.html",parame);
 *
 */

var openWindow = function(name, url, pageParam) {
    api.openWin({
        name: name,
        url: url,
        pageParam: pageParam,
        delay: 200,
        slidBackEnabled: false,
        hScrollBarEnabled: false,
        slidBackEnabled:true,
        bgColor:'#ffffff'
    });
}

var openWindow2 = function(name, url, pageParam) {
    api.openWin({
        name: name,
        url: url,
        pageParam: pageParam,
        delay: 200,
        slidBackEnabled: false,
        hScrollBarEnabled: false,
        allowEdit:true
    });
}

/**
 *更新应用   mam模块
 */
function checkUpdate() {
    var mam = api.require('mam');

    if (mam != undefined) {
        mam.checkUpdate(function(ret, err) {

            var status = ret.status
            if (ret && status == "true") {
                var result = ret.result || "";
                if (result == "") {
                    return;
                }
                if (result.update == true & result.closed == false) {
                    var str = '新版本型号:' + result.version + ';更新提示语:' + result.updateTip + ';下载地址:' + result.source + ';发布时间:' + result.time;
                    api.confirm({
                        title: '有新的版本,是否下载并安装 ',
                        msg: str,
                        buttons: ['确定', '取消']
                    }, function(ret, err) {
                        if (ret.buttonIndex == 1) {
                            if (api.systemType == "android") {
                                api.download({
                                    url: result.source,
                                    report: true
                                }, function(ret, err) {
                                    if (ret && 0 == ret.state) { /* 下载进度 */
                                        api.toast({
                                            msg: "正在下载应用" + ret.percent + "%",
                                            duration: 2000
                                        });
                                    }
                                    if (ret && 1 == ret.state) { /* 下载完成 */
                                        var savePath = ret.savePath;
                                        api.installApp({
                                            appUri: savePath
                                        });
                                    }
                                });
                            }
                        }
                    });
                } else {
                    api.toast({
                        msg: '当前已是最新版本'
                    });
                }
            } else {
                api.toast({
                    msg: '当前已是最新版本'
                });
            }
        });
    }
}




/**
 *安卓回退监听 type 用于主页和非主页
 例： AndroidBackEvent(1, function(data) {
      //成功返回
      });
 */
var exitFlag = false;
var AndroidBackEvent = function(type, successFun) {
    api.addEventListener({
        name: 'keyback'
    }, function(ret, err) {

        console.log("监听安卓回退返回！！" + JSON.stringify(ret));
        if (type == 1) {
            if (!exitFlag) {
                api.toast({
                    msg: '再按一次退出',
                    duration: 2000,
                    location: 'middle'
                });
                exitFlag = true;
            } else {
                api.closeWidget({
                    silent: true
                });
            }
            setTimeout(function() {
                exitFlag = false;
            }, 2000);

            successFun(ret);
        } else {
            successFun(ret);
        }

    });
}


/*
 *
 * 页面加载
 *
 */

function LoadingShow() {

    var _UILoading = api.require("UILoading");

//  var _content = [];
//
//  for (var i = 1; i < 13; i++) {
//      var tPath = 'widget://image/loading/loading-' + i + '.png';
//      _content.push({
//          'frame': tPath
//      });
//  }

	var  _content = [
	{"frame": "widget://image/loading/loading-1.png"},
	{"frame": "widget://image/loading/loading-2.png"},
	{"frame": "widget://image/loading/loading-3.png"},
	{"frame": "widget://image/loading/loading-4.png"},
	{"frame": "widget://image/loading/loading-5.png"},
	{"frame": "widget://image/loading/loading-6.png"},
	{"frame": "widget://image/loading/loading-7.png"},
	{"frame": "widget://image/loading/loading-8.png"},
	{"frame": "widget://image/loading/loading-9.png"},
	{"frame": "widget://image/loading/loading-10.png"},
	{"frame": "widget://image/loading/loading-11.png"},
	{"frame": "widget://image/loading/loading-12.png"},
	];

    console.log(JSON.stringify(_content));

    _UILoading.keyFrame({
        rect: {
            w: 80,
            h: 80
        },
        styles: {
            bg: 'rgba(0,0,0,0)',
            corner: 0,
            interval: 80,
            frame: {
                w: 80,
                h: 80
            }
        },
        content: _content,
        mask: 'rgba(0,0,0,0.1)'
    }, function(ret) {

    });


}

function LoadingClose() {

    var _UILoading = api.require("UILoading");
    _UILoading.closeKeyFrame();

}


/*
 * 下拉模块加载
 *（使用UIPullRefreshFlash模块）
 *
	  fnAddHeaderRefreshingEvent(function(){  //设置下拉刷新
	  api.refreshHeaderLoadDone();
	  });
 *
 *
 *
 *
 */

// 下载刷新方法封装（使用UIPullRefreshFlash模块）
function fnAddHeaderRefreshingEvent(pCallBack) {
    var _content = [];
    for (var i = 1; i < 11; i++) {
        var tPath = 'widget://image/loading/xLoading-' + i + '.png';
        _content.push(tPath);
    }

    api.setCustomRefreshHeaderInfo({
        bgColor: 'rgba(0,0,0,0)',
        loadAnimInterval: 100,
        image: {
            pull: _content,
            load: _content
        }
    }, function(ret, err) {
        if ('function' === typeof pCallBack) {
            pCallBack();
        }
    });

}



/*
 * 上拉加载方法封装
 *
 * 	  fnAddFooterLoadingEvent(function(){  //设置上拉
	  alert("距离底部50触发")
	  });
 */
function fnAddFooterLoadingEvent(pCallBack) {
    api.addEventListener({
        name: 'scrolltobottom',
        extra: {
            threshold: -50 //设置距离底部多少距离时触发，默认值为0，数字类型
        }
    }, function(ret, err) {
        if ('function' === typeof pCallBack) {
            pCallBack();
        }
    });
}


/*
 ** 时间戳转年月日+时分
 ** Date.parse(new Date());//当前时间毫秒数
 */
function changeTimeH(hisTime) {

   if(hisTime==null){
   hisTime="1900-01-01 00:00:00.0"
   }
   date = hisTime.substring(0,19);
   date = date.replace(/-/g,'/');

   timeStamp = Date.parse(new Date(date));//时间转时间搓

    var newTime = new Date(timeStamp);
    var newYear = newTime.getFullYear(); //年
    var newMonth = newTime.getMonth() + 1; //月
    var newDay = newTime.getDate(); //日
    var newHours = newTime.getHours(); //时
    var newMinutes = newTime.getMinutes(); //分
    var newSeconds = newTime.getSeconds(); //秒

    if (newMonth < 10) {
        newMonth = "0" + newMonth;
    }
    if (newDay < 10) {
        newDay = "0" + newDay
    }

    if (newHours < 10) {
        newHours = "0" + newHours
    }
    if (newMinutes < 10) {
        newMinutes = "0" + newMinutes
    }
    if (newSeconds < 10) {
        newSeconds = "0" + newSeconds
    }

    //var timee = newHours+":"+newMinutes;
    var timee = newYear + "-" + newMonth + "-" + newDay
    return timee;
}

function changeTimeH1(timeStamp) {

var replaceStr = '-';//要替换的字符串
var str = timeStamp;//要被替换的字符串

var timeStamp = str.replace(new RegExp(replaceStr,'gm'),'/')

    var newTime = new Date(timeStamp);


    var newYear = newTime.getFullYear(); //年
    var newMonth = newTime.getMonth() + 1; //月
    var newDay = newTime.getDate(); //日
    var newHours = newTime.getHours(); //时
    var newMinutes = newTime.getMinutes(); //分
    var newSeconds = newTime.getSeconds(); //秒

    if (newMonth < 10) {
        newMonth = "0" + newMonth;
    }
    if (newDay < 10) {
        newDay = "0" + newDay
    }

    if (newHours < 10) {
        newHours = "0" + newHours
    }
    if (newMinutes < 10) {
        newMinutes = "0" + newMinutes
    }
    if (newSeconds < 10) {
        newSeconds = "0" + newSeconds
    }

    //var timee = newHours+":"+newMinutes;
    var timee = newYear + "年" + newMonth + "月" + newDay+"日";
    return timee;
}

function changeTimeH2(timeStamp) {


    var newTime = new Date(timeStamp);
    var newYear = newTime.getFullYear(); //年
    var newMonth = newTime.getMonth() + 1; //月
    var newDay = newTime.getDate(); //日
    var newHours = newTime.getHours(); //时
    var newMinutes = newTime.getMinutes(); //分
    var newSeconds = newTime.getSeconds(); //秒

    if (newMonth < 10) {
        newMonth = "0" + newMonth;
    }
    if (newDay < 10) {
        newDay = "0" + newDay
    }

    if (newHours < 10) {
        newHours = "0" + newHours
    }
    if (newMinutes < 10) {
        newMinutes = "0" + newMinutes
    }
    if (newSeconds < 10) {
        newSeconds = "0" + newSeconds
    }

    //var timee = newHours+":"+newMinutes;
    var timee = newYear + "-" + newMonth + "-" + newDay + " " + newHours + ":" + newMinutes + ":" + newSeconds;
    return timee;
}


/*
 *
 * 时间判断
 *
 * 1小时之内显示时分，
 * 1天之后显示月日
 * 1年之后显示年月日
 *
 */
var dateDiff2 = function(hisTime, nowTime) {
	var now = nowTime ? nowTime : new Date().getTime(), diffValue = now - hisTime, result = '', minute = 1000 * 60, hour = minute * 60, day = hour * 24, halfamonth = day * 15, month = day * 30, year = month * 12, _year = diffValue / year, _month = diffValue / month, _week = diffValue / (7 * day), _day = diffValue / day, _hour = diffValue / hour, _min = diffValue / minute;

	var changeTime = new Date();
	changeTime.setTime(hisTime)

	//console.log(changeTime+"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	//console.log(convertDate(changeTime))
	var changeday = changeTime.getDate();
	var changemonth = changeTime.getMonth() + 1;
	var changeyear = changeTime.getFullYear();
	var changeHours = changeTime.getHours();
	//console.log("11" + hisTime + " "   + changeHours)
	var changeMinutes = changeTime.getMinutes();

	if (changeHours < 10) {
		changeHours = "0" + changeHours;
	}
	if (changeMinutes < 10) {
		changeMinutes = "0" + changeMinutes;
	}

	//console.log(_day+"***************************");

	//	if (_year >= 1)
	//		result = parseInt(_year) + "年前";
	//	else if (_month >= 1)
	//		result = parseInt(_month) + "个月前";
	//	else if (_week >= 1)
	//		result = parseInt(_week) + "周前";
	//	 alert(changeHours)
	if (_year >= 1)
		result = changeyear + "-" + changemonth + "-" + changeday;
	else if (_day >= 2)
		result = changemonth + "-" + changeday;
	else if (_day >= 1)
		result = "昨天" + changeHours + ":" + changeMinutes;
	else if (_hour >= 1)
		result = parseInt(_hour) + "个小时前";
	else if (_min >= 1)
		result = parseInt(_min) + "分钟前";
	else
		result = "刚刚";
	return result;
}
var dateDiff = function(hisTime, nowTime) {

       if(hisTime==null){
       hisTime="1900-01-01 00:00:00.0"
       }
       date = hisTime.substring(0,19);
       date = date.replace(/-/g,'/');

       hisTime = Date.parse(new Date(date));//时间转时间搓

    var now = nowTime ? nowTime : new Date().getTime(),
        diffValue = now - hisTime,
        result = '',
        minute = 1000 * 60,
        hour = minute * 60,
        day = hour * 24,
        halfamonth = day * 15,
        month = day * 30,
        year = month * 12,
        _year = diffValue / year,
        _month = diffValue / month,
        _week = diffValue / (7 * day),
        _day = diffValue / day,
        _hour = diffValue / hour,
        _min = diffValue / minute;

    var changeTime = new Date();
    changeTime.setTime(hisTime)

    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();

    if (changeHours < 10) {
        changeHours = "0" + changeHours;
    }
    if (changeMinutes < 10) {
        changeMinutes = "0" + changeMinutes;
    }

    var d = new Date();
    var dd = d.getDate();
    var ddd = dd - changeday;
    // alert(ddd)
    if (ddd < 1) {
        if (_min <= 1) {
            result = '刚刚'
        } else if ((_min > 1) && (_hour < 1)) {
            result = parseInt(_min) + '分钟前'
        } else if ((_hour > 1) && (_day < 1)) {
            result = parseInt(_hour) + '小时前'
        }else{

         result = changeyear + "-" + changemonth + "-" + changeday ;
        }
    } else if (31 > ddd >= 1) {
        // result = changemonth + "-" + changeday;
        result = ddd+'天前';
    } else if (ddd >= 31) {
        result = changeyear + "-" + changemonth + "-" + changeday ;
    }
    return result;
}


var changeTimeeee30 = function(hisTime, nowTime) {

   if(hisTime==null){
   hisTime="1900-01-01 00:00:00.0"
   }
   date = hisTime.substring(0,19);
   date = date.replace(/-/g,'/');

   hisTime = Date.parse(new Date(date));//时间转时间搓
   
   nowTime=Number(nowTime)*1000;
   
	var mss = 1800000-Number(nowTime-hisTime);

    var changeHours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var changeMinutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
    var changeSeconds = (mss % (1000 * 60)) / 1000;


	if (changeHours < 10 && changeHours>0) {
		changeHours = "0" + changeHours;
	}
	if (changeMinutes < 10 && changeMinutes>0) {
		changeMinutes = "0" + changeMinutes;
	}
	if(changeSeconds < 10  && changeSeconds>0){

		changeSeconds= "0" + changeSeconds;
	}

	result = changeMinutes+":"+changeSeconds;
	return result;
}

function formatDuring(mss) {
    var days = parseInt(mss / (1000 * 60 * 60 * 24));
    var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = (mss % (1000 * 60)) / 1000;

	if (hours < 10 && hours>0) {
		hours = "0" + hours;
	}
	if (minutes < 10 && minutes>0) {
		minutes = "0" + minutes;
	}
	if(seconds < 10 && seconds>0){

		seconds= "0" + seconds;
	}

	if(Number(days)>0){
	return (days*24+Number(hours)) + ":" + minutes + ":" + seconds;
	return
	}else{
	return  minutes + ":" + seconds;
	}


}

function changeImg(img){

if(img==null){
return '';
}

var arr = img.split(",")||'';

return arr[0];

}

// 计算年龄
function timm(el) {
    var oldtime = new Date(el).getFullYear();
    var newtime = new Date().getFullYear();
    return newtime - oldtime;
}

//
function jobstatus(index) {
    var aa = ['', '离职-随机到岗', '在职-月内到岗']
    return aa[index];
}



//性别切换
function changeSex2(index) {
    var aa = ['不限', '男', '女']
    return aa[index];
}



function changeXueli(index){

var aa = ['', '小学','初中','高中','本科','硕士','博士','大专']
return aa[index];

}


function changeWorkTime(index){

var aa = ['', '应届生','1年以内','1-3年','3-5年','5-10年','10年以上','不限']
return aa[index];

}

function changeHowTime(index){

var aa = ['', '长期','短期']
return aa[index];

}

function showMoneyyy(index){

var aa = ['', '1k-2k','2k-3k','3k-4k','4k-5k','5k-6k','6k-8k','8k-10k','10k-15k','15k以上']
return aa[index];

}

function changeNewwww(index){

var aa = ['', '直招','中介']
return aa[index];

}

function showEnter(content){

return content.replace(/\n/g, "<br>")

}

function changeDistance(content){

content = Number(content);

var getDist=(content/1000).toFixed(1)+"Km"
return getDist


}

/**
 *云之讯发送短信
 */
function setSMSCode(code4, phone, callBack) {


    //云之讯发送验证码
    smsVerification = api.require('smsVerification');
    smsVerification.sendMessage({
        softVersion: '2014-06-30',
        accountSid: '983def4ac6b7b08dfdffc2553c92088e',
        accountToken: 'e9b5105ca902bca5dac47f162afe9062',
        body: {
            appId: '0568650962be47c6bcfa8cd0ffabbb11',
            templateId: 186059,
            phoneNumber: phone, //输入的手机号
            param: code4 //验证码
        }
    }, function(ret) {


        console.log(code4 + "发送验证码" + JSON.stringify(ret));

        callBack(code4);

    });


}



/**
 *云之讯发送短信
 */
function setSMSCodeTest(phone, callBack) {

    //生成6位随机数
    var code4 = randomNmuber(0, 6);

    //云之讯发送验证码
    smsVerification = api.require('smsVerification');
    smsVerification.sendMessage({
        softVersion: '2017-08-23',
        accountSid: '983def4ac6b7b08dfdffc2553c92088e',
        accountToken: 'e9b5105ca902bca5dac47f162afe9062',
        body: {
            appId: '0568650962be47c6bcfa8cd0ffabbb11',
            templateId: 186059,
            phoneNumber: phone, //输入的手机号
            param: code4 //验证码
        }
    }, function(ret) {

        console.log(code4 + "发送验证码" + JSON.stringify(ret));

        callBack(code4);

    });


}


/*
 ** randomNmuber 产生任意长度随机数字
 ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
 ** 生成3-32位随机串：randomNmuber(true, 3, 32)
 ** 生成43位随机串：randomNmuber(false, 43)
 */
function randomNmuber(randomFlag, min, max) {
    var str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}

/*
 *
 * 个推封装
 *
 */

function pushGeTui() {

    //个推初始化
    var uzgetuisdk = api.require('pushGeTui');
    uzgetuisdk.initialize(function(ret) {

        console.log("个推初始化：" + JSON.stringify(ret));



        var value = "";
        switch (ret.type) {
            case 'cid':
                value = 'cid:' + ret.cid;
                if (api.systemType == 'ios') {
                    registerDeviceToken(uzgetuisdk, ret.cid);
                }
                break;
            case 'payload':
                value = 'payload:' + ret.payload;

                console.warn("重新登录获取到上次透传过来的消息：" + JSON.stringify(ret));

                showHong();

                break;
            case 'occurError':
                value = 'occurError';
                break;
            case 'apns':

                console.warn("透传过来的信息：" + JSON.stringify(ret));
                showHong();

                break;

        }
    });

}

//同步红点！！
function showHong() {

    var parame = {
        values: {
            typeid: $api.getStorage('tokenRole')
        }
    }

    doAjax(getDateHong, "POST", parame, function(data) {

        console.log("透传过来的红点红点红点！！！" + JSON.stringify(data));

        if (data.msg == '111') {

            var oneNumber = data.userLogin.classOne;
            var twoNumber = data.userLogin.classTwo;
            var threeNumber = data.userLogin.classThree;
            var allNumber = oneNumber + twoNumber + threeNumber;
            if (allNumber == 0) {
                return;
            }




            if ($api.getStorage('hongPoint')) {
                var hongPointNumber = Number($api.getStorage('hongPoint')) + allNumber;
                $api.setStorage('hongPoint', hongPointNumber);
                $api.setStorage('hongPoint1', Number($api.getStorage('hongPoint1')) + oneNumber);
                $api.setStorage('hongPoint2', Number($api.getStorage('hongPoint2')) + twoNumber);
                $api.setStorage('hongPoint3', Number($api.getStorage('hongPoint3')) + threeNumber);
            } else {
                $api.setStorage('hongPoint', allNumber);
                $api.setStorage('hongPoint1', oneNumber);
                $api.setStorage('hongPoint2', twoNumber);
                $api.setStorage('hongPoint3', threeNumber);
            }

            var jsfun = 'setHongPoint();';
            if ($api.getStorage('tokenRole') == '1') {

                api.execScript({
                    name: 'index_worker',
                    frameName: 'homePage_frm',
                    script: jsfun
                });

                api.execScript({
                    name: 'index_worker',
                    frameName: 'my',
                    script: jsfun
                });


            } else if ($api.getStorage('tokenRole') == '2') {

                api.execScript({
                    name: 'index_enterprise',
                    frameName: 'homePage_frm',
                    script: jsfun
                });
                api.execScript({
                    name: 'index_enterprise',
                    frameName: 'my',
                    script: jsfun
                });

            }

        } else {

            api.toast({
                msg: data.desc,
                duration: 2000,
                location: 'middle'
            });

        }

    }, function(data) {});

}


function registerDeviceToken(uzgetuisdk, cid) {

    var param = {
        deviceToken: api.deviceToken,
    };
    uzgetuisdk.registerDeviceToken(param, function(ret, err) {
        console.log("注册个推成功返回：" + JSON.stringify(ret) + "||" + api.deviceToken);
    });
}


/*
 * 图片转换成getImgBase64
 * 例如：
 *
 * getImgBase64(ret.destPath,function(dataUrl){
   	console.log(dataUrl);
  	});
 *
 *
 */


function getImgBase64(path, callback) {
    var img = new Image();
    img.src = path;

    //图片加载完成后触发
    img.onload = function() {
        var canvas = document.createElement("canvas");
        //获取绘画上下文
        ctx = canvas.getContext("2d");

        // 获取图片宽高
        var imgWidth = img.width;
        var imgHeight = img.height;

        //设置画布宽高与图片宽高相同
        canvas.width = imgWidth;
        canvas.height = imgHeight;

        //绘制图片
        ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
        //图片展示的 data URI
        var dataUrl = canvas.toDataURL('image/png');
        callback ? callback(dataUrl) : '';
    };
}


//验证邮箱是否正确

function isEmail(str) {
    var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
    return reg.test(str);
}



/*
 *
 * 例子
var a = '1';
var arry = ['1', '2', '3', '4']
var index = indexOf(arry, a);
alert(index); // 弹出0
 *
 */
function indexOf(arr, str) {
    // 如果可以的话，调用原生方法
    if (arr && arr.indexOf) {
        return arr.indexOf(str);
    }

    var len = arr.length;
    for (var i = 0; i < len; i++) {
        // 定位该元素位置
        if (arr[i] == str) {
            return i;
        }
    }

    // 数组中不存在该元素
    return -1;
}

/*
 *
 * 例如：
 * 	 fnVisitor(function(data){

	 if(data){

	 //登录状态执行操作
	 var parame = {}
	 openWindow('mynews_win', './mynews_win.html', parame);
	 }

	 });
 *
 *
 *
 */







/*
 **
 **高德模块aMapLBS定位获取坐标
 */

function aMapLBSLocation(successFun, errorFun) {

    var aMapLBS = api.require('aMapLBS');
    aMapLBS.configManager({
        accuracy: 'tenMeters',
        filter: 1
    }, function(ret, err) {
        if (ret.status) {
            //alert(JSON.stringify(ret));
            aMapLBS.singleLocation({
                timeout: 2
            }, function(ret, err) {
                if (ret.status) {
                    console.log("高德坐标" + JSON.stringify(ret));
                    successFun(ret);
                } else {
                    errorFun(err);
                    api.toast({
                        msg: '定位失败',
                        location: "middle"
                    });
                }

            });
        }
    });

}



function aMapLBSAddress(successFun, errorFun) {

    var aMapLBS = api.require('aMapLBS');
    aMapLBS.configManager({
        accuracy: 'tenMeters',
        filter: 1
    }, function(ret, err) {
        if (ret.status) {
			aMapLBS.singleAddress({
			    timeout: 2
			}, function(ret, err) {
				console.log("定位:"+JSON.stringify(ret));

			    if (ret.status) {
			       successFun(ret);
			    }else {

                    errorFun(err);
                    api.toast({
                        msg: '定位失败',
                        location: "middle"
                    });
                }
			});
        }
    });

}



function aMapLBSAddressBMAP2222(successFun, errorFun) {

var bMap = api.require('bMap');


if(api.systemType=='ios'){

bMap.initMapSDK(function(ret) {


    if (ret.status) {



bMap.getLocation({
    accuracy: '100m',
    autoStop: true,
    filter: 1
}, function(ret, err) {
    if (ret.status) {

		bMap.getNameFromCoords({
		    lon: ret.lon,
		    lat: ret.lat
		}, function(ret, err) {
		    if (ret.status) {
				successFun(ret);
		    }
		});


    } else {
	        errorFun(err);
	        api.toast({
	            msg: '定位失败',
	            location: "middle"
	        });
    }
});




    }
});

}else {


bMap.getLocation({
    accuracy: '100m',
    autoStop: true,
    filter: 1
}, function(ret, err) {
    if (ret.status) {

    	console.log("定位"+JSON.stringify(ret))

		bMap.getNameFromCoords({
		    lon: ret.lon,
		    lat: ret.lat
		}, function(ret, err) {
		console.log("位置"+JSON.stringify(ret))
		    if (ret.status) {
				successFun(ret);
		    }
		});


    } else {
	        errorFun(err);
	        api.toast({
	            msg: '定位失败',
	            location: "middle"
	        });
    }
});



}




}




function aMapLBSAddressBMAP(successFun, errorFun) {

var bMap = api.require('bMap');


if(api.systemType=='ios'){

bMap.initMapSDK(function(ret) {


    if (ret.status) {



bMap.getLocation({
    accuracy: '100m',
    autoStop: true,
    filter: 1
}, function(ret, err) {
    if (ret.status) {

   		successFun(ret);
//		bMap.getNameFromCoords({
//		    lon: ret.lon,
//		    lat: ret.lat
//		}, function(ret, err) {
//		    if (ret.status) {
//				successFun(ret);
//		    }
//		});


    } else {
	        errorFun(err);
	        api.toast({
	            msg: '定位失败',
	            location: "middle"
	        });
    }
});




    }
});

}else {


bMap.getLocation({
    accuracy: '100m',
    autoStop: true,
    filter: 1
}, function(ret, err) {
    if (ret.status) {

    	console.log("定位"+JSON.stringify(ret))
		successFun(ret);
//		bMap.getNameFromCoords({
//		    lon: ret.lon,
//		    lat: ret.lat
//		}, function(ret, err) {
//		console.log("位置"+JSON.stringify(ret))
//		    if (ret.status) {
//				successFun(ret);
//		    }
//		});


    } else {
	        errorFun(err);
	        api.toast({
	            msg: '定位失败',
	            location: "middle"
	        });
    }
});



}




}


//时间转换成时间戳
function getTimestamp(time) {

    var timeTamp = Date.parse(new Date(time.replace(/-/g, "/"))); //指定时间的毫秒数

    return timeTamp;

}


//时间戳转化成时间
function getDateTime(timeNumber) {
    var changeTime = new Date();
    changeTime.setTime(timeNumber)

    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();

    if (changemonth < 10) {
        changemonth = "0" + changemonth;
    }
    if (changeday < 10) {
        changeday = "0" + changeday;
    }

    var result = changeyear + "-" + changemonth + "-" + changeday;

    return result

}

//时间戳转化成时间
function getDateTime1(timeNumber) {
    var changeTime = new Date();
    changeTime.setTime(timeNumber)

    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();

    if (changemonth < 10) {
        changemonth = "0" + changemonth;
    }
    if (changeday < 10) {
        changeday = "0" + changeday;
    }

    var result = changeyear + "-" + changemonth;

    return result

}

/*
 *
 * 打开高德app导航
 *
 */

function openGaoDeAPP(lat, lon) {

    var navigator = api.require('navigator');

    navigator.installed({
        target: 'aMap'
    }, function(ret, err) {
        if (ret.status) {

            navigator.aMapNavigation({
                end: {
                    lon: lon,
                    lat: lat
                },
                dev: 0,
                strategy: 'fast'
            });


        } else {

            api.toast({
                msg: "未检测到高德app",
                duration: 2000,
                location: 'middle'
            });


        }
    });


}





/*
 *
 * 打开百度app导航
 *
 */

function openBaiDuAPP(lat, lon, mylat, mylon) {

    var navigator = api.require('navigator');

    navigator.installed({
        target: 'bMap'
    }, function(ret, err) {
        if (ret.status) {

            navigator.bMapNavigation({
                start: { // 起点信息.
                    lon: lon, // 经度.
                    lat: lat, // 纬度.
                    name: ''
                },
                end: { // 终点信息.
                    lon: mylon, // 经度
                    lat: mylat, // 纬度
                    name: ''
                },
                mode: 'driving'
            });


        } else {

            api.toast({
                msg: "未检测到百度app",
                duration: 2000,
                location: 'middle'
            });


        }
    });


}

//本项目的时间转换
function changeBenTime(hisTime, type) {


    if (hisTime == null) {
        hisTime = "1900-01-01 00:00:00"
    }
    date = hisTime.substring(0, 19);
    date = date.replace(/-/g, '/');

    hisTime = Date.parse(new Date(date)); //时间转时间搓

    var changeTime = new Date();
    changeTime.setTime(hisTime)


    var changeday = changeTime.getDate();
    var changemonth = changeTime.getMonth() + 1;
    var changeyear = changeTime.getFullYear();
    var changeHours = changeTime.getHours();

    var changeMinutes = changeTime.getMinutes();

    if (changemonth < 10) {
        changemonth = "0" + changemonth;
    }
    if (changeday < 10) {
        changeday = "0" + changeday;
    }

    if (changeHours < 10) {
        changeHours = "0" + changeHours;
    }
    if (changeMinutes < 10) {
        changeMinutes = "0" + changeMinutes;
    }

    if (type == 1) {
        var result = changemonth + "-" + changeday + " " + changeHours + ":" + changeMinutes;
    } else if (type == 2) {

        var result = changemonth + "月" + changeday + "日";

    } else {
        var result = changemonth + "月" + changeday + "日" + " " + changeHours + ":" + changeMinutes;
    }


    return result

}







//判断游客登录跳转登录页
function fnVisitor(pCallBack) {

    if (!$api.getStorage('userId')) {

        pCallBack(false);

        //			var parame = {
        //			}
        //			openWindow("login_win", "../../../html/login_win.html");
        api.closeToWin({
            name: 'login_win'
        });

        return;
    } else {
        //返回true说明登录
        pCallBack(true);
        return;
    }
}




function apiClose() {
    api.closeWin();
}



/**
*
* MD5 (Message-Digest Algorithm)
* http://www.webtoolkit.info/
*
**/
var MD5 = function (string) {
 function RotateLeft(lValue, iShiftBits) {
  return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
 }
 function AddUnsigned(lX,lY) {
  var lX4,lY4,lX8,lY8,lResult;
  lX8 = (lX & 0x80000000);
  lY8 = (lY & 0x80000000);
  lX4 = (lX & 0x40000000);
  lY4 = (lY & 0x40000000);
  lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
  if (lX4 & lY4) {
   return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
  }
  if (lX4 | lY4) {
   if (lResult & 0x40000000) {
    return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
   } else {
    return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
   }
  } else {
   return (lResult ^ lX8 ^ lY8);
  }
  }
  function F(x,y,z) { return (x & y) | ((~x) & z); }
  function G(x,y,z) { return (x & z) | (y & (~z)); }
  function H(x,y,z) { return (x ^ y ^ z); }
 function I(x,y,z) { return (y ^ (x | (~z))); }
 function FF(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 };
 function GG(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 };
 function HH(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 };
 function II(a,b,c,d,x,s,ac) {
  a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
  return AddUnsigned(RotateLeft(a, s), b);
 };
 function ConvertToWordArray(string) {
  var lWordCount;
  var lMessageLength = string.length;
  var lNumberOfWords_temp1=lMessageLength + 8;
  var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
  var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
  var lWordArray=Array(lNumberOfWords-1);
  var lBytePosition = 0;
  var lByteCount = 0;
  while ( lByteCount < lMessageLength ) {
   lWordCount = (lByteCount-(lByteCount % 4))/4;
   lBytePosition = (lByteCount % 4)*8;
   lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
   lByteCount++;
  }
  lWordCount = (lByteCount-(lByteCount % 4))/4;
  lBytePosition = (lByteCount % 4)*8;
  lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
  lWordArray[lNumberOfWords-2] = lMessageLength<<3;
  lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
  return lWordArray;
 };
 function WordToHex(lValue) {
  var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
  for (lCount = 0;lCount<=3;lCount++) {
   lByte = (lValue>>>(lCount*8)) & 255;
   WordToHexValue_temp = "0" + lByte.toString(16);
   WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
  }
  return WordToHexValue;
 };
 function Utf8Encode(string) {
  string = string.replace(/\r\n/g,"\n");
  var utftext = "";
  for (var n = 0; n < string.length; n++) {
   var c = string.charCodeAt(n);
   if (c < 128) {
    utftext += String.fromCharCode(c);
   }
   else if((c > 127) && (c < 2048)) {
    utftext += String.fromCharCode((c >> 6) | 192);
    utftext += String.fromCharCode((c & 63) | 128);
   }
   else {
    utftext += String.fromCharCode((c >> 12) | 224);
    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
    utftext += String.fromCharCode((c & 63) | 128);
   }
  }
  return utftext;
 };
 var x=Array();
 var k,AA,BB,CC,DD,a,b,c,d;
 var S11=7, S12=12, S13=17, S14=22;
 var S21=5, S22=9 , S23=14, S24=20;
 var S31=4, S32=11, S33=16, S34=23;
 var S41=6, S42=10, S43=15, S44=21;
 string = Utf8Encode(string);
 x = ConvertToWordArray(string);
 a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
 for (k=0;k<x.length;k+=16) {
  AA=a; BB=b; CC=c; DD=d;
  a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
  d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
  c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
  b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
  a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
  d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
  c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
  b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
  a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
  d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
  c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
  b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
  a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
  d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
  c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
  b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
  a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
  d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
  c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
  b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
  a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
  d=GG(d,a,b,c,x[k+10],S22,0x2441453);
  c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
  b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
  a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
  d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
  c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
  b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
  a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
  d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
  c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
  b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
  a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
  d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
  c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
  b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
  a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
  d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
  c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
  b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
  a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
  d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
  c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
  b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
  a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
  d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
  c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
  b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
  a=II(a,b,c,d,x[k+0], S41,0xF4292244);
  d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
  c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
  b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
  a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
  d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
  c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
  b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
  a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
  d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
  c=II(c,d,a,b,x[k+6], S43,0xA3014314);
  b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
  a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
  d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
  c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
  b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
  a=AddUnsigned(a,AA);
  b=AddUnsigned(b,BB);
  c=AddUnsigned(c,CC);
  d=AddUnsigned(d,DD);
 }
 var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
 return temp.toLowerCase();
}






/**
 * Created by andy on 14-12-25.
 */
/**
 *
 *  Secure Hash Algorithm (SHA1)
 *  http://www.webtoolkit.info/
 *
 **/

function SHA1(msg) {

    function rotate_left(n, s) {
        var t4 = ( n << s ) | (n >>> (32 - s));
        return t4;
    };

    function lsb_hex(val) {
        var str = "";
        var i;
        var vh;
        var vl;

        for (i = 0; i <= 6; i += 2) {
            vh = (val >>> (i * 4 + 4)) & 0x0f;
            vl = (val >>> (i * 4)) & 0x0f;
            str += vh.toString(16) + vl.toString(16);
        }
        return str;
    };

    function cvt_hex(val) {
        var str = "";
        var i;
        var v;

        for (i = 7; i >= 0; i--) {
            v = (val >>> (i * 4)) & 0x0f;
            str += v.toString(16);
        }
        return str;
    };


    function Utf8Encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;

    msg = Utf8Encode(msg);

    var msg_len = msg.length;

    var word_array = new Array();
    for (i = 0; i < msg_len - 3; i += 4) {
        j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 |
            msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
        word_array.push(j);
    }

    switch (msg_len % 4) {
        case 0:
            i = 0x080000000;
            break;
        case 1:
            i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
            break;

        case 2:
            i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
            break;

        case 3:
            i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
            break;
    }

    word_array.push(i);

    while ((word_array.length % 16) != 14) word_array.push(0);

    word_array.push(msg_len >>> 29);
    word_array.push((msg_len << 3) & 0x0ffffffff);


    for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {

        for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i];
        for (i = 16; i <= 79; i++) W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);

        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for (i = 0; i <= 19; i++) {
            temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 20; i <= 39; i++) {
            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 40; i <= 59; i++) {
            temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        for (i = 60; i <= 79; i++) {
            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B, 30);
            B = A;
            A = temp;
        }

        H0 = (H0 + A) & 0x0ffffffff;
        H1 = (H1 + B) & 0x0ffffffff;
        H2 = (H2 + C) & 0x0ffffffff;
        H3 = (H3 + D) & 0x0ffffffff;
        H4 = (H4 + E) & 0x0ffffffff;

    }

    var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

    return temp.toLowerCase();

}

//////////////////////////////////////////////md5////////////////
















//绑定极光
function tooAjpush() {
    var ajpush = api.require('ajpush');
    if (api.systemType == 'ios') {
        var param = {
            alias: $api.getStorage("allUser").user_id
        };
        ajpush.bindAliasAndTags(param, function(ret) {
            var statusCode = ret.statusCode;
            console.log("绑定别名成功" + statusCode + "||" + $api.getStorage("allUser").user_id);
            if (statusCode == 6002) {
                tooAjpush();
            }

            setListenerAjpush();
            setListenerAjpushIos();

        });
    } else {
        ajpush.init(function(ret) {
            if (ret && ret.status) {
                var param = {
                    alias: $api.getStorage("allUser").user_id
                };
                ajpush.bindAliasAndTags(param, function(ret) {


                    var statusCode = ret.statusCode;
                    console.log("绑定别名返回状态" + statusCode + "||" + $api.getStorage("allUser").user_id);
                    if (statusCode == 6002) {
                        tooAjpush();
                    }
                    setListenerAjpush();
                    setListenerAjpushAndor();

                });
            }
        });

    }
}


//监听通知以及消息
function setListenerAjpush() {

    var ajpush = api.require('ajpush');
    ajpush.setListener(
        function(ret) {
            var id = ret.id;
            var title = ret.title;
            var content = ret.content;
            var extra = ret.extra;

	        console.log(JSON.stringify(ret));


			var jsonstr =eval('(' + ret.content + ')')

			if(jsonstr.tcid=='2'){

			$api.setStorage('hong2_'+$api.getStorage("allUser").user_id,'1');

			var jsfun = 'hongMain5();';
			api.execScript({
			    name: 'root1',
			    script: jsfun
			});

			}else{

			$api.setStorage('hongMain1_'+$api.getStorage("allUser").user_id,'1');


			var jsfun = 'changeNewHongMain4();';
			api.execScript({
			    name: 'root1',
			    script: jsfun
			});

//			var jsfun = 'showHong();';
//			api.execScript({
//			    name: 'root1',
//			    frameName: 'main1_win',
//			    script: jsfun
//			});

			}




        }
    );

}



//通知被点击安卓
function setListenerAjpushAndor() {

    api.addEventListener({
        name: 'appintent'
    }, function(ret, err) {
        if (ret && ret.appParam.ajpush) {
            var ajpush = ret.appParam.ajpush;
            var id = ajpush.id;
            var title = ajpush.title;
            var content = ajpush.content;
            var extra = ajpush.extra;
            console.log(JSON.stringify(ret));

//			alert(JSON.stringify(ret));

        }
    })

}


//通知被点击ios
function setListenerAjpushIos() {

    api.addEventListener({
        name: 'noticeclicked'
    }, function(ret, err) {
        if (ret && ret.value) {
            var ajpush = ret.value;
            var content = ajpush.content;
            var extra = ajpush.extra;
            console.log(JSON.stringify(ret));

            var jsfun = 'hongPoint();';
            api.execScript({
                name: 'root',
                frameName: 'main_win',
                script: jsfun
            });

        }
    })


}


//微信支付
function payWX() {

    var wxPay = api.require('wxPay');
    wxPay.config({
        apiKey: 'wx92919d8a0efc26b9',
        mchId: '1490777982',
        partnerKey: 'e10adc3949ba59abbe56e057f20f883e',
        notifyUrl: 'www.baidu.com'
    }, function(ret, err) {
        if (ret.status) {

            console.log("配置key正确" + JSON.stringify(ret));

            var nonono = randomWord(false, 30);

            wxPay.pay({
                description: 'hello:测试测试',
                totalFee: '1',
                tradeNo: nonono,
            }, function(ret, err) {

                console.log("支付正确正确...." + JSON.stringify(ret) + "支付错误错误...." + JSON.stringify(err));
                if (ret.status) {
                    //alert(ret.result);
                } else {
                    //alert(err.code);
                }
            });

        } else {
            alert(JSON.stringify(err));
        }
    });


}


//支付宝支付
function payZF() {


    var aliPayPlus = api.require('aliPayPlus');
    aliPayPlus.config({
        appId: '2016081600255523',
        rsaPriKey: 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQClMv0WoKfCGN+eJsWtkeH+9MtAK/arN450AEoGAC2udqgidMLAzIP2/y1lZzs7wssAW0mzdDM3WawmFdEQocRqXET9Ef99TEMc40RzwjJZsDuUDJ3KgUo5H9a9Hm3LhWqYI8pF9gaGsXyOzMssQDqqDSi9A7AhkE3jafsGs3r/op2GAyCQWfFifVq0tv9M1d7+3ErOCJWIkRbGGr5mFFl6S8QpIREMSGhvASMtsMjT9IawGhA/CbtBVMd3L6K96KilicXDEpDeRWLy1iMz5jS3MoVgwME3Yj5PGt38Z+n1tx2fFFPgzpQhpgLJeHDGl1mtB0qafHkLaNdhZZ2hP+xtAgMBAAECggEAFXipGHXNGBcviVi0vLiHTSH4AOE18E8KPt2CwYDobxKRC9ltLq3mQQYtmk5ujnfk9qjmzWI+/eSz0UdooubDpqdTeCkMsfZliq2nSfxlmu6i770sDRP816vhtzbrQlaW4itUsP8nHf6Xl9/aUGgQt+V59Ac0r0gYN4Sg0eAmDm+YonIvhGVL9BNZBAq7Q/udptSzBWQXIZUn92iK8C2rcv8Bi6j4sl2W2VgAZHn00Z9tO7y/m7AZhtHBUP7sXMV3Jle+ThdgqjCApEnmywW218bPVxUvajCvLC9d9VQnJLff7bWoFKRLC7TIwsk87LbwjBiCOYVxe3a3wwSZBwH7QQKBgQDiMVvL4Srx/spkFndY36lqerlROKNsOzLkq7qrRdVKcr2Ej2GH95uNz4O6yXJTkSdSwqEhxFfKz+So6SsVKQDObCRzSGXVFSV7ctQPDKQ7UTWexfIKXofJjLFWwscgS84lYssFmuXpaTkKoaXTFiTJQRWubVaZkKacQGDWqvc/WQKBgQC6+ACnA8qL8NqKrrnPdXEraVFh/QxOVq0SKzCy/dilVvHUxMUdYxuJVDWGyre3kp4cz6jMFZoo+iUpHHdwUXg79zCl6gEaOnQH0Hn2MRmlUpVcetBxQsK7imAWQuGhThgx86DUThKC7c6Ct6lFNjEg80Z5Eoey2iTkOIKU9stnNQKBgQCsGI/WTEhHfOryQeGmPe4BdMRg1q4IX/Y1468QNv60OR6WqBy1vZ+dwuBgEnsot8zqe+jq7x840PoRxe4gmGTjqYYGLHRGLmOpTFGp7Z1bAEvCtKqWVxwLLj+TWnj0ypha+5KqfhMlhwh+XUT0mOl+MkXTw57bEiKhyZ2kVsntaQKBgENsBUg07Mh0DUrvYR/3uNyvuOI+Dz78sKKZopEZSxOse75/SpmjUJ3AGSFHXuK643t+Qt99dr8KHXZqxoNhTZtKM2fRL56Wr5rVyfVGlXnxgtz7iMkfCvv4FVhRu+2gLMdulHOax8AhI1QuCMNlnGfGcoZccUTEt4L5AdXX/Vd1AoGAVqw2vs83klWuMBgfB/qBIkkGvt1R7IqNXt7oVZBLFp0g2vH3i1iRpOtx0G0BWvs4cu8BAAIMeOxma+c3hLNsBzeIpRknnlGSsaFgGunUmu8090Km3qWLNAyp1GUWnemjQAc3n3nN1KBFx3UebGw8URIwdRK+qWCL8oi7A4BGRlQ=',
    }, function(ret, err) {

        var nonono = randomWord(false, 30);

        aliPayPlus.pay({
            subject: '订单名',
            body: '订单描述',
            amount: '0.01',
            tradeNO: nonono,
            rsa2: true
        }, function(ret, err) {
            api.alert({
                title: '支付结果',
                msg: JSON.stringify(ret),
                buttons: ['确定']
            });
        });


    });


}


//////////////////////后台发起支付/////////////////


/////////////////////////微信////////////////////////
/*	例子：
	var data = {
	}
	payServerWX(data,function(successData) {
	//成功回调执行函数
	}, function(errorData) {
	//失败回调执行函数
	})
*/


function payServerWX(data, successFun, errorFun) {

var wxPay = api.require('wxPay');
wxPay.payOrder({
    apiKey: 'wxa15f6b72c349863c',
    orderId: data.prepayid, //prepayid
    mchId: '1515729741',
    nonceStr: data.noncestr, //noncestr
    timeStamp: data.timestamp, //timestamp
    package: 'Sign=WXPay',
    sign: data.sign //sign
}, function (ret, err) {
    if (ret.status) {
      console.log(JSON.stringify(ret) + "支付成功返回参数");
      //alert(JSON.stringify(ret) + "支付成功返回参数");
      successFun(ret);
    } else {
      console.log(err.code + "支付失败跳转返回参数");
      //alert(JSON.stringify(err) + "支付失败返回参数");
      errorFun(err);
      return
    }
});


}


/*	例子：
	var data = {
	}
	payServerZFB(data,function(successData) {
	//成功回调执行函数
	}, function(errorData) {
	//失败回调执行函数
	})
*/

////////////////////支付宝//////////////////

function payServerZFB(data, successFun, errorFun) {

  //打开支付宝支付
  var aliPayPlus = api.require('aliPayPlus');
  aliPayPlus.payOrder({
    orderInfo: data.msgsss
  }, function (ret, err) {

    console.log(JSON.stringify(ret) + "||" + JSON.stringify(err));

    //alert(JSON.stringify(ret)+"||"+JSON.stringify(err))

    if (ret.statusCode == '9000' || ret.code == '9000') {

      console.log(JSON.stringify(ret) + "支付成功返回参数");
      successFun(ret);

    } else {

      console.log(JSON.stringify(err) + "支付失败返回参数");
      errorFun(err);
      return

    }
  });

}
/*
 ** randomWord 产生任意长度随机字母数字组合
 ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
 ** 生成3-32位随机串：randomWord(true, 3, 32)
 ** 生成43位随机串：randomWord(false, 43)
 */

function randomWord(randomFlag, min, max) {
    var str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}



/**
 *
 * 打开相册
 *
 * 	openCamera(0,function(url){
 *  });
 *
 *
 */

function openCamera(type, sucessFun) {

    var typeArray = ['camera', 'album']

    api.getPicture({
        sourceType: typeArray[type],
        encodingType: 'png',
        mediaValue: 'pic',
        destinationType: 'url',
        allowEdit: false,
        quality: 80,
        saveToPhotoAlbum: true
    }, function(ret, err) {

        console.log("打开摄像机返回的数据" + JSON.stringify(ret));

        if (ret && ret.data != '') {

            var dataImg = ret.data;
            return sucessFun(dataImg);

        } else {
            //alert(JSON.stringify(err));
        }
    });


}


/**
 *
 * 压缩单张图片
 *
 */

function yasuo(dataImg, successFun) {

    LoadingShow();
    var imageFilter = api.require('imageFilter');
    var imgName = 'clue_picture_' + Math.random() + '.jpg';
    imageFilter.compress({
        img: dataImg,
        quality: 0.8,
        scale: 1,
        save: {
            album: false,
            imgPath: 'fs://clue/',
            imgName: imgName
        }
    }, function(ret, err) {

        LoadingClose();
        var path = ret.status ? api.fsDir + '/clue/' + imgName : images[i];
        console.log('压缩图片！！！' + JSON.stringify(ret) + "路径" + path);
        //调用上传头像的接口

        successFun(path);

    });
}

/**
 *
 * 压缩多张图片
 *
 */
var yaSuoImgggg = [];

function yasuoImgs(all, index, successFun) {
    if (index == 0) {
        yaSuoImgggg = [];
    }
    var imageFilter = api.require('imageFilter');
    LoadingShow();
    console.log("赫尔"+all.length + "||" + index);
    if (all.length <= index) {

        LoadingClose();
        //完成执行的方法
        console.log("缓存完成!!!" + JSON.stringify(yaSuoImgggg));

        return successFun(yaSuoImgggg);

    }

    if (api.systemType == 'ios') {

        var UIMediaScanner = api.require('UIMediaScanner');
        UIMediaScanner.transPath({
            path: all[index].path,
        }, function(ret, err) {
            if (ret) {

                var imgName = 'clue_picture_' + Math.random() + '.jpg';
                imageFilter.compress({
                    img: ret.path,
                    quality: 0.8,
                    scale: 1,
                    save: {
                        album: false,
                        imgPath: 'fs://clue/',
                        imgName: imgName
                    }
                }, function(ret, err) {


                    var path = ret.status ? api.fsDir + '/clue/' + imgName : images[i];
                    console.log('压缩图片！！！' + JSON.stringify(ret) + "路径" + path);
                    //调用上传头像的接口
                    yaSuoImgggg.push(path);
                    yasuoImgs(all, index + 1, successFun);


                });

            } else {
                alert(JSON.stringify(err));
            }
        });


    } else {


        var imgName = 'clue_picture_' + Math.random() + '.jpg';
        imageFilter.compress({
            img: all[index].path,
            quality: 0.8,
            scale: 1,
            save: {
                album: false,
                imgPath: 'fs://clue/',
                imgName: imgName
            }
        }, function(ret, err) {
//         alert("数据解决"+JSON.stringify(ret))

            var path = ret.status ? api.fsDir + '/clue/' + imgName : images[i];
            console.log('压缩图片！！！' + JSON.stringify(ret) + "路径" + path);
            //调用上传头像的接口
            yaSuoImgggg.push(path);
            yasuoImgs(all, index + 1, successFun);


        });

    }

}



/**
 *
 * 打开图片多张
 *
 */
function openAlbum(maxNumber, successFun) {

    var UIMediaScanner = api.require('UIMediaScanner');
    UIMediaScanner.open({
        type: 'picture',
        column: 4,
        classify: true,
        max: maxNumber,
        sort: {
            key: 'time',
            order: 'desc'
        },
        texts: {
            stateText: '已选择*项',
            cancelText: '取消',
            finishText: '完成'
        },
        styles: {
            bg: '#fff',
            mark: {
                icon: '',
                position: 'bottom_left',
                size: 20
            },
            nav: {
                bg: '#eee',
                stateColor: '#000',
                stateSize: 18,
                cancelBg: 'rgba(0,0,0,0)',
                cancelColor: '#000',
                cancelSize: 18,
                finishBg: 'rgba(0,0,0,0)',
                finishColor: '#000',
                finishSize: 18
            }
        },
        scrollToBottom: {
            intervalTime: -1,
            anim: true
        },
        exchange: true,
        rotation: true
    }, function(ret) {
        if (ret) {

            if (ret.eventType == 'confirm') {
                console.log("打开多张图片" + JSON.stringify(ret));
                successFun(ret);
            }


        }
    });


}



function showBigPicture(picArr, index) {

    console.log("图片图片！！" + picArr);

    var photoBrowser = api.require('photoBrowser');
    photoBrowser.open({
        images: picArr,
        activeIndex: index,
        placeholderImg: 'widget://res/img/apicloud.png',
        bgColor: '#000'
    }, function(ret, err) {
        if (ret) {

            if (ret.eventType == "click") {
                photoBrowser.close();
            }

        } else {
            //alert(JSON.stringify(err));
        }
    });

}


function savePicture(urlll) {

api.confirm({
    title: '是否确定下载图片',
    msg: '是否确定下载图片',
    buttons: ['确定', '取消']
}, function(ret, err) {
    var index = ret.buttonIndex;
    if(index==1){

	api.download({
		url : urlll,
		report : true,
		cache : true,
		allowResume : true
	}, function(ret, err) {
		if (ret.state == 1) {
			api.saveMediaToAlbum({
				path : ret.savePath
			}, function(ret, err) {
				if (ret) {
                api.toast({
                    msg: '保存成功',
                    duration: 2000,
                    location: 'middle'
                });
				} else {
				}
			});
		} else {
		}
	});

    }

});


}

/**
 *
 * 同步缓存多张图片到本地
 * saveToLoaclImg('数组数据',0);
 */

var shuzu = [];

function saveToLoaclImg(all, index, successFun) {

    LoadingShow();

   if(all){


    if (all.length <= index) {

        LoadingClose();
        //完成执行的方法
        console.log("缓存完成!!!" + JSON.stringify(shuzu));

        successFun(shuzu);
        return;

    }

    api.imageCache({
        url: all[index],
        encode: false,
        policy: 'cache_else_network',
        thumbnail: false
    }, function(ret, err) {

        console.log(JSON.stringify(all)+"缓存图片"+JSON.stringify( ret)+"|||"+JSON.stringify(err)+"|||");

        shuzu.push(ret.url);
        saveToLoaclImg(all, index + 1, successFun);
    });
 }
}



/**
 *
 * 同步一张图片到本地
 * saveToLoaclImgOne('图片地址',successFun);
 */


function saveToLoaclImgOne(img, successFun) {



    //var aaa=[];
    //aaa.push('/var/mobile/Containers/Data/Application/C115EF46-8D72-42BD-BCC5-A574CCAC2B00/Library/Caches/APICloud/Cache/45e891085af2b9b579164c6c73da1c9f_thumb.png');
    //
    //var compactPicture = api.require('compactPicture');
    //compactPicture.HittingPic({
    //  picpatharray: aaa,
    //  size: 1
    //}, function(ret) {
    //
    //	console.log(ret.states[0]);
    //
    //var imageFilter = api.require('imageFilter');
    //imageFilter.getAttr({
    //  path:ret.states[0]
    //},function( ret, err ){
    //  if( ret.status ){
    //      alert( JSON.stringify( ret ) );
    //  }else{
    //      alert( JSON.stringify( err ) );
    //  }
    //});
    //
    //
    //});
    //
    //return;


    if (img == '' || img == null) {
        successFun('../../image/zanweitu/book2.png');
        return;
    }

    LoadingShow();
    api.imageCache({
        url: img,
        encode: false,
        policy: 'cache_else_network',
        thumbnail: true
    }, function(ret, err) {
        LoadingClose();
        console.log("缓存图片" + JSON.stringify(ret) + "|||" + JSON.stringify(err) + "|||");

        if (err) {
            successFun('../../image/zanweitu/book2.png');
        } else {

            if (api.systemType == 'ios') {

                var compactPicture = api.require('compactPicture');
                compactPicture.HittingPic({
                    picpatharray: [ret.url],
                    size: 3
                }, function(ret) {
                    //alert(JSON.stringify(ret));
                    successFun(ret.states[0]);

                });

            } else {
                successFun(ret.url);
            }

            //console.log(ret.url);
            //var imageFilter = api.require('imageFilter');
            //imageFilter.getAttr({
            //  path: ret.url
            //},function( ret, err ){
            //  if( ret.status ){
            //      alert( JSON.stringify( ret ) );
            //  }else{
            //      alert( JSON.stringify( err ) );
            //  }
            //});
            //
            //alert(ret.url);
            //console.log(ret.url);
            //return;



        }



    });

}


function countDownTime(time1, time2) {

    //alert(timetrans(time1)+"|||||"+timetrans(time2));


    var time = Number(time1) + 1800000 - Number(time2);

    if (time > 0) {

        //时间转换成秒
        var newMinutes = parseInt(time / 60000);
        //小时
        var newHours = parseInt(newMinutes / 60);
        //分钟
        newMinutes = newMinutes - newHours * 60;

        return "剩余:" + newMinutes + "分钟";
    } else {
        return "订单失效";
    }

}

//时间搓 转时间
function timetrans(date) {
    var date = new Date(date); //如果date为10位不需要乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return Y + M + D + h + m + s;
}

//返回天数
function countDownTime2(time) {


    if (time > 0) {
        //时间转换成分
        var newMinutes = parseInt(time / 60000);

        //小时
        var newHours = parseInt(newMinutes / 60);

        var newDays = parseInt(newMinutes / 1440)

        var bHours = newHours - newDays * 24;

        return "剩余:" + newDays + "天" + bHours + "小时";

    } else {
        return "已逾期";
    }

}


///手机号//
function fnPhone(phonee) {
    var phone = phonee.substring(0, 3) + "****" + phonee.substring(7, 11)
    return phone;
}


//计算折扣
function discount(max, min) {

    if (max == 0) {
        return "0折";
    }
    var max = max || 0;
    var min = min || 0;
    var zheke = (min / max).toFixed(2);
    //console.log(max+"|||"+min+"||"+zheke);
    return zheke * 10 + "折";
}



/**
 *
 *db模块
 *
 *全部
 *
 */


////打开db
//function openDataBase() {
//
//  var db = api.require('db');
//  db.openDatabase({
//      name: 'foot'
//  }, function(ret, err) {
//
//      creatMyDB(); //新建一个表用来存足迹数据
//
//  });
//}
//
//
////全部全部全部
//function creatMyDB() {
//
//  var userId = $api.getStorage('userId');
//  var bdName = 'a' + userId;
//
//  var sql = "CREATE TABLE'" + bdName + "'(id varchar(255),type varchar(255),createtime varchar(255),other varchar(255))";
//
//  //更新SQL
//  upDataSql(sql, function() {
//      //
//  });
//
//}



//执行SQL
function upDataSql(sql, fun) {
    console.log("新增SQL!!!!!"+sql);
    var db = api.require('db');
    db.executeSql({
        name: 'msg',
        sql: sql
    }, function(ret, err) {
        if (ret.status) {
            fun(ret.status);
            console.log("第一次进入app新建聊天表成功！！！！and！！！新增条数返回状态||||"+JSON.stringify(ret));
        } else {
            console.log(JSON.stringify(err.msg));
        }
    });
}




/*
 * 	查询SQL

	var userId = $api.getStorage('userId');
	var bdName='a'+userId;
	readSQL('SELECT * FROM "'+ bdName +'" ORDER BY createtime DESC', function(succData) {

	alert(JSON.stringify(succData));
	});
 */
function readSQL(sql, fun) {
    var db = api.require('db');
    db.selectSql({
        name: 'msg',
        sql: sql
    }, function(ret, err) {
        if (ret.status) {

            //console.log("查询表返回数据"+JSON.stringify(ret));
            var data = ret.data;
            fun(data);
        } else {
            console.log(JSON.stringify(err));
            //api.({
            //	"title" : "提示",
            //	"msg" : "数据查询失败"
            //}, function(ret, err) {
            //});
        }
    });
}



/*
 *
 *	删除表
 * 	delectSql(function(){

	});
 *
 */

function delectSql(fun) {

    var userId = $api.getStorage('userId');
    var bdName = 'a' + userId;

    var db = api.require('db');
    db.executeSql({
        name: 'foot',
        sql: 'DELETE FROM ' + bdName
    }, function(ret, err) {
        if (ret.status) {
            fun(ret.status);
        } else {
            console.log(JSON.stringify(err.msg));
        }
    });
}







// 打开分享
function fnFen(shareData) {

    api.openFrame({
        name: 'z_share_frm',
        url: './z_share_frm.html',
        bounces: false,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto',
        },
        pageParam: shareData,
        hScrollBarEnabled: false,
        vScrollBarEnabled: false,
    });

}


/*
 * 往本地添加一条是数据
 */

function saveLocal(idd, type) {
    var userId = $api.getStorage('userId');
    var bdName = 'a' + userId;
    var timestamp = Date.parse(new Date());

    //获得的idd
    //执行查询语句，如果有数据不添加。否则新增一条

    readSQL('SELECT * FROM "' + bdName + '" where id="' + idd + '"', function(succData) {

        console.log("插入的时候查看时候有相同的数据：" + JSON.stringify(succData));

        if (succData.length == 0) {

            var sql = "INSERT INTO '" + bdName + "'(id,type,createtime)";
            sql = sql + "VALUES ('" + idd + "','" + type + "','" + timestamp + "')";

            upDataSql(sql, function() {
                console.log("没有相同的数据插入成功一条！！！");
            });

        }

    });




}

//////////////////////////////////超级团队 /////////////////
var convertFullDateTime = function(date) {
	var date = new Date();
	date.setTime(date);
	return date.Format("yyyy-MM-dd hh:mm:ss")
}


var convertFullDateTime2 = function(data) {
	var date = new Date();
	date.setTime(data);
	return date.Format("yyyy-MM-dd hh:mm")
}

Date.prototype.Format = function(fmt) {//author: meizz
	var o = {
		"M+" : this.getMonth() + 1, //月份
		"d+" : this.getDate(), //日
		"h+" : this.getHours(), //小时
		"m+" : this.getMinutes(), //分
		"s+" : this.getSeconds(), //秒
		"q+" : Math.floor((this.getMonth() + 3) / 3), //季度
		"S" : this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
	if (new RegExp("(" + k + ")").test(fmt))
		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

function isFirst(funs) {
	var isFirst = $api.getStorage("isFirst") || "";

	var db = api.require('db');
	if (isFirst == "") {
		//首次加载创建数据库

		db.openDatabase({
			name : 'msg'
		}, function(ret, err) {
			if (ret.status) {

				var sql = "CREATE TABLE msg(duration varchar(255),contentextra varchar(111)  DEFAULT NULL,contenttext varchar(111) DEFAULT NULL, conversationType varchar(111) DEFAULT NULL, extra varchar(2000) DEFAULT NULL,messageDirection varchar(111) DEFAULT NULL, messageid varchar(111) NOT NULL, objectname varchar(111) DEFAULT NULL,receivedtime varchar(111) DEFAULT NULL, senderuserid varchar(111) DEFAULT NULL, sendstatus varchar(111) DEFAULT NULL, sendtime varchar(111) DEFAULT NULL,targetid varchar(111) DEFAULT NULL, userid varchar(111) DEFAULT NULL, createtime varchar(111) DEFAULT NULL,status varchar(111) DEFAULT NULL,other1 varchar(111) DEFAULT NULL,other2 varchar(111) DEFAULT NULL,other3 varchar(111) DEFAULT NULL,poi varchar(111) DEFAULT NULL,latitude varchar(111) DEFAULT NULL,longitude varchar(111) DEFAULT NULL)";

				//更新SQL
				upDataSql(sql, function() {
					//
				});


			} else {
				api.toast({
					msg : '系统初始化失败'
				});
			}
		});
	} else {
		db.openDatabase({
			name : 'msg'
		}, function(ret, err) {
			funs();
			console.log("不是第一次进入app打开数据库成功！！！！"+JSON.stringify(ret));
//			api.execScript({
//				script : 'initMessage();',
//				name : "root"
//			});
		});
	}

	$api.setStorage("isFirst", "isFirst");

}



//////////////////初始化融云//////////////////

function laheiRongYun(userIddd){

var rong = api.require('rongCloud2');
// 之前调用 init 和 connect 的代码省略
rong.addToBlacklist({
    userId:userIddd
}, function(ret, err) {
//  api.toast({
//      msg:'拉黑成功',
//      duration: 2000,
//      location: 'middle'
//  });
})

}

function remoreLaheiRongYun(userIddd){

var rong = api.require('rongCloud2');
// 之前调用 init 和 connect 的代码省略
rong.removeFromBlacklist({
    userId:userIddd
}, function(ret, err) {
//  api.toast({
//      msg:'取消拉黑成功',
//      duration: 2000,
//      location: 'middle'
//  });
})

}

function initRongYun() {
    var rongCloud2 = api.require('rongCloud2');

    rongCloud2.init(function(ret, err) {
        if (ret.status == 'error') {
            api.toast({
                msg: err.code
            });
        }

        var rongToken = $api.getStorage("allUser").rytoken;

        rongCloud2.setOnReceiveMessageListener(function(ret, err) {

            console.log("融云返回！！！！message " + JSON.stringify(ret.result.message));
            var extra = ret.result.message.content.extra || "";
            console.warn(extra + "aa");
            var conversationType = ret.result.message.conversationType;
            var targetId = ret.result.message.targetId;

            rongCloud2.setConversationNotificationStatus({
                    conversationType: conversationType,
                    targetId: targetId,
                    notificationStatus: 'DO_NOT_DISTURB'
                }, function(ret, err) {
                    if (ret.status == 'success') {
                        // d.resolve(ret);
                    } else {
                        err.where = "rong.setConversationNotificationStatus 1";
                        //d.reject(err);
                    }
                })

				//监听到发送信息保存
				saveMessage(ret.result.message);

//          if (extra != "" && extra.indexOf("REPORT") >= 0) {
//              //显示报道的小红点
//              api.execScript({
//                  script: 'baodao(1);',
//                  name: "root"
//              });
//          } else if (extra != "" && extra.indexOf("NEWS") >= 0) {
//              api.execScript({
//                  script: 'baodao(0);',
//                  name: "root"
//              });
//          } else {
//              saveMessage(ret.result.message);
//          }

        })


        rongCloud2.setConnectionStatusListener(function(ret, err) {
            var status = ret.result.connectionStatus
            if (status == "KICKED") {
			   $api.rmStorage('allUser');

                api.alert({
                    msg: "您的账号已在其他设备登陆"
                }, function(ret, err) {
                    //coding...
				api.rebootApp();

                });

            }
        });


        rongCloud2.connect({
            token: rongToken
        }, function(ret, err) {

        	//alert(JSON.stringify(ret));
            console.warn("链接融云返回参数"+JSON.stringify(ret)+"||||失败码："+JSON.stringify(err));

            if(ret.status!='success'){

            	if(err.code!='34001'){

            	initRongYun();

            	}

            }

//          initMessage();
        });

    });

    api.addEventListener({
        name: 'noticeclicked'
    }, function(ret, err) {

    });
}


var saveMessage = function(message) {
	var contentextra = message.content.extra;
	var contenttext = message.content.text;
	var conversationType = message.conversationType;

	var extra = message.extra;
	var messageDirection = message.messageDirection;
	var messageId = message.messageId;
	var objectName = message.objectName;
	var receivedTime = message.receivedTime;
	var senderUserId = message.senderUserId;
	var sentStatus = message.sentStatus;
	var sentTime = message.sentTime;
	var duration = message.duration || "";
	var targetId = message.targetId || "";
	var userId = $api.getStorage("allUser").user_id;

	var poi = '';
	var latitude = '';
	var longitude = '';


	if (openChatWindow == false) {

		$api.setStorage('hong_'+$api.getStorage("allUser").user_id,'1');

		var jsfun = 'hongMain5();';
		api.execScript({
		    name: 'root1',
		    script: jsfun
		});

		console.warn(conversationType)
		if (conversationType == "PRIVATE") {
			console.log(senderUserId);

					var isRemind = $api.getStorage("isOpen_"+userId) || "";

					if (isRemind == "") {
						api.notification({
							notify : {
								content : '你收到了一条信息',
								title : '忙么事'
							}
						}, function(ret, err) {
						});
					}
						var  rongCloud2    =  api.require("rongCloud2")

						rongCloud2.setConversationNotificationStatus({
							conversationType : conversationType,
							targetId : targetId,
							notificationStatus : 'NOTIFY'
						}, function(ret, err) {
							if (ret.status == 'success') {
									console.log("-----------------");
							} else {
								err.where = "rong.setConversationNotificationStatus 1";
								//			        d.reject(err);
							}
						})

//			var name = $api.getStorage("name" + senderUserId) || "";
//			if (name == "") {
//				var parame = {
//					values : {
//						userId : senderUserId
//					}
//				}
//				doAjax(GETINFO, "POST", parame, function(data) {
//					name = data.data.nickname;
//					var isRemind = $api.getStorage("isRemind") || "";
//					if (isRemind == "") {
//						api.notification({
//							notify : {
//								content : convertMsg(objectName, contenttext),
//								title : name
//							}
//						}, function(ret, err) {
//						});
//					}
//						var  rongCloud2    =  api.require("rongCloud2")
//
//						rongCloud2.setConversationNotificationStatus({
//							conversationType : conversationType,
//							targetId : targetId,
//							notificationStatus : 'NOTIFY'
//						}, function(ret, err) {
//							if (ret.status == 'success') {
//									console.log("-----------------");
//							} else {
//								err.where = "rong.setConversationNotificationStatus 1";
//								//			        d.reject(err);
//							}
//						})
//				}, function() {
//				})
//			} else {
//
//				var isRemind = $api.getStorage("isRemind") || "";
//				if (isRemind == "") {
//					api.notification({
//						notify : {
//							content : convertMsg(objectName, contenttext),
//							title : name
//						}
//					}, function(ret, err) {
//					});
//
//						var  rongCloud2  =   api.require("rongCloud2");
//						rongCloud2.setConversationNotificationStatus({
//							conversationType : conversationType,
//							targetId : targetId,
//							notificationStatus : 'NOTIFY'
//						}, function(ret, err) {
//							if (ret.status == 'success') {
//								//d.resolve(ret);
//								console.log("-----------------");
//							} else {
//
//								//d.reject(err);
//							}
//						})
//				}
//			}
		}

	}
	if (message.objectName == "RC:ImgMsg") {
		contenttext = message.content.imageUrl;
		console.log(contenttext)

	}

	if (message.objectName == "RC:VcMsg") {
		contenttext = message.content.voicePath;
		duration = message.content.duration
	}

	if (message.objectName == "RC:LBSMsg") {


	poi = message.content.poi;
	latitude = message.content.latitude;
	longitude = message.content.longitude;
	contenttext =message.content.imagePath;

//	alert(poi+"|"+latitude+"|"+longitude+"|"+contenttext);
	}

	console.log("extra  :  " + extra)

	var sql = "INSERT INTO msg(duration,contentextra,          contenttext,   		conversationType,     		extra,      	messageDirection,		 messageid,		  objectname,	receivedtime,senderuserid,sendstatus,sendtime,targetid,userid,createtime,status,poi,longitude,latitude)";
	sql = sql + "VALUES ('" + duration + "','" + contentextra + "','" + contenttext + "' ,'" + conversationType + "' ,'" + extra + "','" + messageDirection + "','" + messageId + "' ,'" + objectName + "' ,'" + receivedTime + "','" + senderUserId + "','" + sentStatus + "','" + sentTime + "','" + targetId + "','" + userId + "','" + new Date().getTime() + "','1','" + poi + "','" + longitude + "','" + latitude + "')";

	upDataSql(sql, function() {
		console.log("保存消息成功");
		//initAppIconBadge();


		api.execScript({
			script : 'initMessage("'+conversationType+'");',
			name : "root1"
		});

//		api.execScript({
//			script : 'initMessage("new");',
//			name : "chat_win",
//			frameName : "chat_frm"
//		});

	});
}




//退出 融云
function exitRong(fun) {
    var rongCloud2 = api.require('rongCloud2');
    // 之前调用 init 和 connect 的代码省略
    rongCloud2.disconnect({
        isReceivePush: false
    }, function(ret, err) {
        if ('success' == ret.status) {
            api.toast({
                msg: '断开连接成功!'
            });
            fun();
        }
    });
    // 断开，且不再接收 Push
}

/**
 *ibm  监听事件
 * @param {Object} name
 * @param {Object} funs
 */
function ibmAddEventListener(name, funs) {
	api.addEventListener({
		name : name
	}, function(ret, err) {
		funs(ret);
	});
}


function setLightKey(key) {

    var lightKey = "<span class='orange'>" + keyword + "</span>";
    if (key && key.indexOf(keyword) >= 0) {
        key = key.split(keyword).join(lightKey);

    }

    return key;
}


function setPhone(phone) {

    return phone.substring(0, 3) + "-" + phone.substring(3, 7) + "-" + phone.substring(7, 11);

}

//验证函数
/**
 * if(!isCanPass(value,type)){
 *
 *	api.toast({
 *	  msg: '请输入正确的团队ID',
 *	 duration: 2000,
 *	  location: 'middle'
 *	});
 *
 * }
 *
 *
 */

function isCanPass(value, type) {
    var regBox = {
        regMobile: /^[0-9]*$/ //判断是否是数字
    }

    if (type == 1) {
        var rvalue = regBox.regMobile.test(value);
        if (!(rvalue && value)) {
            //验证不通过
            return false;
            return;
        } else {
            //验证通过
            return true;
        }
    }



}

// 拨打电话
function dadianhua(num){
   isVisitorLogin(function(data) {

	if (data) {

	  api.call({
	      type: 'tel_prompt',
	      number: num
	  });

 	}

	});

}



/////////////////////////////////////////////////////

//if (!checkNumber(gopage_val)) {
//alert("请输入正确页数(数字)");
//return false;
// }
function checkNumber(theObj) {
  var reg = /^[0-9]+.?[0-9]*$/;
  if (reg.test(theObj)) {
    return true;
  }
  return false;
}




/**
 * 删除文件
 *
 * fs模块
 *
 */

function fsDelectFile(fileUrl, successFun, errFun) {

	console.log("传递过来的地址：       |||||" + fileUrl);

	var pathhhh;
	if (api.systemType == 'ios') {
		pathhhh = fileUrl;
	} else {
		pathhhh = 'fs:' + fileUrl
	}

	console.log("删除文件的地址：       |||||" + pathhhh);

	var fs = api.require('fs');
	fs.remove({
		path : pathhhh
	}, function(ret, err) {
		if (ret.status) {

			console.log("删除文件成功！！！！！！" + JSON.stringify(ret));
			//成功回调
			successFun(ret);

		} else {

			console.log("删除文件失败！！！！！！" + JSON.stringify(err));
			//失败回调
			errFun(err);

		}
	});

}


function changeImggg(imggg){

//return imggg+'?imageMogr2/gravity/North/crop/1280x558'
return imggg+'?imageView2/1/w/720/h/372';

}

function getCtrlCCC(el){

var dateeee=$api.attr(el, 'dateeee');

var clipBoard = api.require('clipBoard');
clipBoard.set({
    value: dateeee
}, function(ret, err) {
    if (ret.status) {
		api.toast({
            msg: '已成功复制',
            duration: 2000,
            location: 'middle'
        });
    } else {
        alert(JSON.stringify(err));
    }
});

}

	var longpress=0;
	var timeOutEvent='';
    //开始长按
    function touchstart(el){
		longpress=0;
		idd= $api.attr(el, 'idd');
//		console.log(idd+'弹框');
        timeOutEvent=setTimeout(function(){

		getCtrlCCC(el);


	    longpress=1;
         },500);
//		 var touch = el.touches[0];
//       touchY = touch.clientY;
    }

    //触摸移动
     function touchmove(el){

        clearTimeout(timeOutEvent);
        timeOutEvent = 0;
//      var touch = el.touches[0]
//      if(Math.abs(touch.clientY - touchY) < 10){
//          el.preventDefault();
//      }


    }

     function touchend(el){
     	idd= $api.attr(el, 'idd');
     	a_num = $api.attr(el, 'a_num');
//		console.log(idd+'详情');
        clearTimeout(timeOutEvent);
        if(timeOutEvent!=0 && longpress==0){//点击

        }
        return false;
    }
	
	function getPayType(type){
	
	if(type=='1'){
	return '支付宝支付';
	}else{
	return '微信支付';
	}
	
	
	}

	
	//计算价格
	function changeMoney(getArrayyy){
	
	console.log(getArrayyy+"|||||||||||||||||计算价格");
	
	var allMoney=0;
	for(var i=0; i<getArrayyy.length;i++){
	
	if(getArrayyy[i].g_prcie_kill>0){
	allMoney=allMoney+Number(getArrayyy[i].g_prcie_kill)*Number(getArrayyy[i].car_number);
	}else{
	allMoney=allMoney+Number(getArrayyy[i].g_price_now)*Number(getArrayyy[i].car_number);
	}
	
	}
	
	return allMoney;
	
	}


	//计算价格
	function changeMoney22(money1,money2,number){
	
	
    if(Number(money1)>0){
    var allMoney = Number(money1)*Number(number);
    }else{
     var allMoney = Number(money2)*Number(number);
    }
	
	
	return allMoney;
	
	}
	
	
/////////////////////////页面跳转///////////////////////////////////////////
function openOneShop(id){

  var parame = {
    idd:id
  };
  openWindow("shop_homepage_win", "../../html/main2/shop_homepage_win.html", parame);


}




function openShareWinToShare(allDate){

    api.openFrame({
    	name: 'z_share',
    	url: '../../html/main4/z_share.html',
    	bounces: false,
    	rect: {
    		x: 0,
    		y: 0,
    		w: 'auto',
    		h: 'auto'
    	},
    	pageParam: allDate,
    	hScrollBarEnabled: false,
    	vScrollBarEnabled: false,
    });

}


/////////////////
// isVisitorLogin(function(data) {
//
// if (data) {
//
// }
// });

function isVisitorLogin(pCallBack) {

    if (!$api.getStorage('allUser')) {


    	pCallBack(false);

    	openWindow("login_win", "../../html/login_win.html");


    	return;

    } else {
    	//返回true说明登录
    	pCallBack(true);

    	return;
    }

}



//////////////////////////////添加个数//////////////////////////////////












